const websocket = require('ws')

const ws = new websocket.Server({//创建端口8000的websocket服务
    port:8000
})

let clients = {}
let clientNum = 0

ws.on("connection",(client)=>{
    //监听，连接客户端

    //给每个连接的客户端创建一个名字
    client.name = ++clientNum
    clients[client.name] = client // 创建键值对  "1":client实例

    //用client实例监听四个常用事件 open, message, error, close
    client.on("message", (msg) => {
        console.log("用户"+client.name+"说: "+msg)
        broadcast(client,msg)
    })
    client.on("error", () => {
        if(err){
            console.log(err)
        }
    })
    client.on("close", () => {
        broadcast(client)
        console.log("用户"+client.name+"下线了！！！")
        delete clients[client.name]
    })
})

//广播方法
function broadcast(msg){
    for(let key in clients){
        clients[key].send("用户"+client.name+"说:"+msg)
    }
}







